package com.android.djlmapp.activity.kaika;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.djlmapp.R;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.listener.read.GetPhotoUrlListener;
import com.android.djlmapp.model.eventbus.FaceRzInfo;
import com.android.djlmapp.model.home.Info;
import com.android.djlmapp.tools.global.TakePhotoUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.read.GetPhotoUrlUtils;
import com.android.djlmapp.view.carmer.CameraView;
import com.android.readcard.dialog.MyUsualyDialog;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.android.readcard.global.PrefReadCardTools;
import com.android.readcard.utils.ImageTools;
import com.google.gson.Gson;
import com.jph.takephoto.model.LubanOptions;
import com.lzy.okgo.callback.StringCallback;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnCompressListener;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

import static com.android.djlmapp.R.id.takepic;

@RuntimePermissions
public class FaceCarmerActivity extends AppCompatActivity implements OnClickListener {

    private CameraView view;
    private ImageView iv_discount //丢弃
            , iv_ok        //确认
            , iv_takepic  //拍照
            , camera_back;  //返回
    private File fileAll;//文件夹
    private String mZhengPhoto = "";  //正面照
    private String file_photo = "";
    private String user_name = "";
    private String user_card = "";
    private String bluetoothName = "";
    private File file;
    private File[] files;
    String filePath = "";
    private MyUsualyDialog dialog2;
    private List<String> imagePathList;
    private ImageView camera_fz;
    private RelativeLayout ll_title;

    private String path = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_facecarmer);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        // 实名认证页传递的数据
        Bundle extras = getIntent().getExtras();
        file_photo = extras.getString("FILE_PHOTO");
        user_name = extras.getString("USER_NAME");
        user_card = extras.getString("USER_CARD");
        bluetoothName = extras.getString("BluetoothName");


        //获取与应用相关联的路径
        filePath = TakePhotoUtils.getFileDirectory() + TakePhotoUtils.STR_PATH;
        fileAll = new File(filePath);
        FaceCarmerActivityPermissionsDispatcher.NeedsPermissionWithCheck(this);
    }

    //设置android app 的字体大小不受系统字体大小改变的影响
    @Override
    public Resources getResources() {
        Resources res = null;
        try {
            res = super.getResources();
            Configuration config = new Configuration();
            config.setToDefaults();
            res.updateConfiguration(config, res.getDisplayMetrics());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("项目异常", "--onLivenessSuccess----getResources------" + e.toString());
        }
        return res;
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
        initData();
    }

    private void initData() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            makeRootDirectory("/sdcard/mt");
            makeRootDirectory(filePath);
        } else {
            ToastUtils.showShortToast(FaceCarmerActivity.this, "请确认插入SD卡");
        }
    }

    private void initView() {
        view = findViewById(R.id.view);
        ll_title = findViewById(R.id.ll_titleface);

        iv_discount = findViewById(R.id.discount);
        camera_fz = findViewById(R.id.camera_fz);
        iv_ok = findViewById(R.id.ok);
        iv_takepic = findViewById(takepic);
        camera_back = findViewById(R.id.camera_back);
        iv_takepic.setOnClickListener(this);
        iv_ok.setOnClickListener(this);
        camera_fz.setOnClickListener(this);
        iv_discount.setOnClickListener(this);
        camera_back.setOnClickListener(this);
        initWindow(ll_title);
    }


    @Override
    public void onClick(View arg0) {

        switch (arg0.getId()) {
            case R.id.ok:
                iv_ok.setEnabled(false);
                // 得到该路径文件夹下所有的文件
                files = fileAll.listFiles();
                if (files != null && files.length > 0) {
                    // 图片列表     File.separator
                    imagePathList = new ArrayList<String>();
                    file = files[0];
                    compressOld(file);
                } else {
                    iv_ok.setEnabled(true);
                    deleteFile(fileAll);
                    iv_takepic.setVisibility(View.VISIBLE);
                    iv_takepic.setClickable(true);
                    iv_ok.setVisibility(View.GONE);
                    iv_discount.setVisibility(View.GONE);
                    iv_takepic.setEnabled(true);
                    MyApplication.showToast("未获取到照片,请重新拍照2");
                }
                break;
            case R.id.takepic:
                deleteFile(fileAll);
                iv_takepic.setEnabled(false);
                view.takePicture(new CameraView.OnTakePicFinishListener() {
                    @Override
                    public void onTakePicFinish(String bigFile, String smallFile) {
                        iv_takepic.setClickable(false);
                        iv_takepic.setVisibility(View.INVISIBLE);
                        iv_ok.setClickable(true);
                        iv_discount.setClickable(true);
                        iv_ok.setVisibility(View.VISIBLE);
                        iv_discount.setVisibility(View.VISIBLE);
                    }
                }, filePath, 100, CameraView.FlashMode.OFF);

                break;
            case R.id.discount:
                iv_takepic.setEnabled(true);
                iv_takepic.setVisibility(View.VISIBLE);
                iv_takepic.setClickable(true);
                iv_discount.setVisibility(view.INVISIBLE);
                iv_discount.setClickable(false);
                iv_ok.setClickable(false);

                iv_ok.setVisibility(View.INVISIBLE);
                view.startPreView();
                if (filePath != null) {
                    ImageTools.deleteAllPhoto(FaceCarmerActivity.this, filePath);
                }
                break;
            case R.id.camera_back:
                if (filePath != null) {
                    ImageTools.deleteAllPhoto(FaceCarmerActivity.this, filePath);
                }
                backResult(0);
                break;
            case R.id.camera_fz:
                iv_takepic.setEnabled(true);
                iv_takepic.setClickable(true);
                iv_takepic.setVisibility(View.VISIBLE);
                iv_ok.setVisibility(View.GONE);
                iv_discount.setVisibility(View.GONE);
                if (filePath != null) {
                    ImageTools.deleteAllPhoto(FaceCarmerActivity.this, filePath);
                }
                view.switchCamera();
                break;
        }
    }

    private void backResult(int code) {
        if (code == 1) {
            Intent intent = new Intent();
            intent.putExtra("backCode", code);
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    private void compressOld(final File mfile) {
        LubanOptions option = new LubanOptions.Builder().create();
        Luban.compress(FaceCarmerActivity.this, mfile)
                .putGear(Luban.CUSTOM_GEAR)
                .setMaxHeight(option.getMaxHeight())
                .setMaxWidth(option.getMaxWidth())
                .setMaxSize(option.getMaxSize() / 1024)
                .launch(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        dialog2 = new MyUsualyDialog(FaceCarmerActivity.this,
                                R.layout.wait_item);
                        dialog2.setCanceledOnTouchOutside(false);
                        dialog2.show();
                    }

                    @Override
                    public void onSuccess(File file) {
                        yaSuoSuccess(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("项目异常", "------压缩失败onError------" + e.getMessage());
                        ToastUtils.showShortToast(FaceCarmerActivity.this, "压缩失败err");
                    }
                });
    }

    private void yaSuoSuccess(File file) {
        path = file.getPath();
        if (path != null) {
            if (checkIsImageFile(path)) {
                imagePathList.add(path);
            }
            GetPhotoUrlUtils.getPhotoUrl(path, new GetPhotoUrlListener() {
                @Override
                public void backPhotoUrl(int backType, String photoUrl) {
                    deleteFile(fileAll);
                    if (backType == 1) {
                        // 获取头像正面照url== filePhoto
                        try {
                            // 身份证头像url
                            mZhengPhoto = URLEncoder.encode(file_photo, "UTF-8");
                            if (!TextUtils.isEmpty(photoUrl)) {
                                // 活体检测图片url
                                photoUrl = URLEncoder.encode(photoUrl, "UTF-8");
                                faceNet(photoUrl);
                            } else {
                                errSet();
                                ToastUtils.showShortToast(FaceCarmerActivity.this, "未获取到活体检测头像URL11");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            errSet();
                            ToastUtils.showShortToast(FaceCarmerActivity.this, "未获取到身份证头像URL33");
                        }
                    } else {
                        errSet();
                        ToastUtils.showShortToast(FaceCarmerActivity.this, photoUrl);
                    }
                }
            });
        } else {
            errSet();
            MyApplication.showToast("未获取到照片,请重新拍照3");
        }
    }

    /**
     * 拍照错误时候的设置
     */
    private void errSet() {
        if (dialog2 != null) {
            dialog2.dismiss();
        }
        iv_ok.setEnabled(true);
        iv_takepic.setVisibility(View.VISIBLE);
        iv_takepic.setClickable(true);
        iv_ok.setVisibility(View.GONE);
        iv_discount.setVisibility(View.GONE);
        iv_takepic.setEnabled(true);
        view.startPreView();
    }


    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            } else {
//                MyApplication.showToast("该文件夹已经存在");
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 失去焦点的时候要清空该路径下的文件
        if (filePath != null) {
            ImageTools.deleteAllPhoto(FaceCarmerActivity.this, filePath);
        }
        iv_takepic.setVisibility(View.VISIBLE);
        iv_takepic.setClickable(true);
        iv_takepic.setEnabled(true);
        iv_ok.setVisibility(View.GONE);
        iv_discount.setVisibility(View.GONE);
    }

    /**
     * 检查扩展名，得到图片格式的文件
     *
     * @param fName 文件名
     * @return
     */
    private boolean checkIsImageFile(String fName) {
        boolean isImageFile = false;
        // 获取扩展名
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1,
                fName.length()).toLowerCase();
        if (FileEnd.equals("jpg") || FileEnd.equals("png") || FileEnd.equals("gif")
                || FileEnd.equals("jpeg") || FileEnd.equals("bmp")) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }

    /***
     * 新增删除方法
     */
    public void deleteFile(File file) {
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                    this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代

                }
            }
        }
    }

    private void faceNet(final String filename) {

        MyApplication.getInstance().getHttpTools().faceDuiBi(mZhengPhoto, filename, new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                try {
                    ImageTools.deleteAllPhoto(FaceCarmerActivity.this,
                            Environment.getExternalStorageDirectory() + "/wltlib/");

                    iv_ok.setEnabled(true);
                    Gson gson1 = new Gson();
                    Info facePhotoInfo = gson1.fromJson(response.body(), Info.class);
                    int code = facePhotoInfo.getCode();
                    if (code < 1000) {
                        dialog2.dismiss();
                        PrefReadCardTools.setString(FaceCarmerActivity.this, "BluetoothName", bluetoothName);
                        FaceRzInfo faceRzInfo = new FaceRzInfo();
                        faceRzInfo.setFace_image(filename); // 人脸识别照片
                        faceRzInfo.setFace_ok("1"); // 认证结果 1 成功  2 失败
                        faceRzInfo.setSfz_card(user_card);
                        faceRzInfo.setSfz_name(user_name);
                        faceRzInfo.setSfzPhoto(file_photo); // 身份证头像
                        Event<FaceRzInfo> event = new Event<>(EventCodes.EventFaceCode.A, faceRzInfo);
                        EventBusUtil.sendEvent(event);
                        // 对比成功跳转界面

                        backResult(1);
                    } else {
                        // 识别失败
                        dialog2.dismiss();
                        PrefReadCardTools.setString(FaceCarmerActivity.this, "BluetoothName", bluetoothName);

                        ImageTools.deleteAllPhoto(FaceCarmerActivity.this, Environment.getExternalStorageDirectory()
                                + "/wltlib/");
                        FaceRzInfo faceRzInfo = new FaceRzInfo();
                        faceRzInfo.setFace_image(filename); // 人脸识别照片
                        faceRzInfo.setFace_ok("2"); // 认证结果 1 成功  2 失败
                        faceRzInfo.setSfz_card(user_card);
                        faceRzInfo.setSfz_name(user_name);
                        faceRzInfo.setSfzPhoto(file_photo); // 身份证头像
                        Event<FaceRzInfo> event = new Event<>(EventCodes.EventFaceCode.A, faceRzInfo);
                        EventBusUtil.sendEvent(event);

                        // 对比失败跳转界面
                        backResult(1);
                    }
                } catch (Exception e) {
                    errSet();
                    ToastUtils.showShortToast(FaceCarmerActivity.this, "数据解析异常2");
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                errSet();
                ToastUtils.showShortToast(FaceCarmerActivity.this, "网络异常，请重新识别2");
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        });
    }

    /**
     * 设置控件的padding值（// 防止标题栏和状态栏重叠）
     */
    public void initWindow(ViewGroup viewGroup) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            viewGroup.setPadding(0, getStatusBarHeight(), 0, 0);
        }
    }

    /**
     * 获得状态栏的高度
     */
    public int getStatusBarHeight() {

        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void NeedsPermission() {

    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FaceCarmerActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void ShowRationale(final PermissionRequest request) {

        request.proceed();
        isFirstPer = false;
    }


    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void PermissionDenide() {
        if(isFirstPer){return;}
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setMessage("请允许需要的权限")
                .setNegativeButton("确定", (dialog, which) -> finish()).show();

    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void NeverAskAgin() {
        if(isFirstPer){
            return;
        }
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setMessage("请允许需要的权限")
                .setNegativeButton("确定", (dialog, which) -> finish()).show();
    }
    private boolean isFirstPer = true;
}
